//
//  MenuView.m
//  YuDou
//
//  Created by qiupeng on 2018/6/24.
//  Copyright © 2018年 yingqi. All rights reserved.
//

#import "MenuView.h"
#import "MenuViewCell.h"
#import "AnchorGroup.h"
#import "CollectionGameCell.h"

#define MenuCellID @"MenuCellID"

@interface MenuView()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic ,weak) IBOutlet UICollectionView *collectionView;
@property (nonatomic ,weak) IBOutlet UIPageControl *pageControl;

@end

@implementation MenuView

+ (instancetype)menuView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"MenuView" owner:nil options:nil] firstObject];
}
 
- (void)awakeFromNib
{
    [super awakeFromNib];
    
    self.autoresizingMask = UIViewAutoresizingNone;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"MenuViewCell" bundle:nil] forCellWithReuseIdentifier:MenuCellID];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize =  self.collectionView.bounds.size;
    self.collectionView.collectionViewLayout = layout;

}

- (void)setGroups:(NSArray<AnchorGroup *> *)groups
{
    _groups = groups;
    [self.collectionView reloadData];
}

#pragma mark - CollecetionView DataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_groups.count) {
        NSInteger pageNum = (_groups.count - 1) / 8 + 1;
        self.pageControl.numberOfPages = pageNum;
        if ( pageNum <= 1 ){
            self.pageControl.hidden = YES;
        }
        return pageNum;
    }else{
        return 0;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MenuViewCell *cell = (MenuViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:MenuCellID forIndexPath:indexPath];
    [self setupCellDataWithCell:cell indexPath:indexPath];
    
    return cell;
}

- (void)setupCellDataWithCell:(MenuViewCell *)cell indexPath:(NSIndexPath *)indexPath
{
    int loc = (int)indexPath.item * 8;
    int len = 8;
    if (loc + len > _groups.count) { // 对越界进行判断处理
        len = (int)_groups.count - loc;
    }
    cell.groups = [_groups subarrayWithRange:NSMakeRange(loc, len)];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = (NSInteger)(scrollView.contentOffset.x / scrollView.width + 0.5);
}
@end
